package com.health.warehouse.scheduled;


import com.health.api.client.UserClient;
import com.health.api.model.hospital.GetHospitalInfoRequest;
import com.health.api.model.hospital.HospitalVO;
import com.health.common.auth.service.TokenService;
import com.health.common.model.user.LoginUser;
import com.health.warehouse.mapper.WarehouseMapper;
import com.health.warehouse.model.entity.Warehouse;
import com.health.websocket.handler.InventoryWebSocketHandler;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author zhexueqi
 * @ClassName InventoryMonitor
 * @since 2024/9/3    10:26
 */
@Component
public class InventoryMonitor {

    @Resource
    private WarehouseMapper warehouseMapper;
    @Resource
    private TokenService tokenService;

    @Resource
    private UserClient userClient;

    @Resource
    private InventoryWebSocketHandler webSocketHandler;

    @Scheduled(fixedRate = 60000)  // 每分钟检查一次
    public void checkInventoryLevels() {
        LoginUser loginUser = tokenService.getLoginUser();
        if (loginUser == null) {
            return;
        }
        //获取医院信息
        GetHospitalInfoRequest getHospitalInfoRequest = new GetHospitalInfoRequest();
        getHospitalInfoRequest.setHospitalAccount(loginUser.getUserAccount());
        HospitalVO hospitalInfo = userClient.getHospitalInfo(getHospitalInfoRequest);

        List<Warehouse> lowStockItems = warehouseMapper.checkLowStockItems(hospitalInfo.getId());
        //拼接所有低库存的仓库信息
        StringBuilder sb = new StringBuilder();
        for (Warehouse warehouse : lowStockItems) {
            sb.append(warehouse.getWarehouseName()).append(",");
        }


        //发送websocket消息
        if (!lowStockItems.isEmpty()) {
            String alertMessage = String.format("库存告警：{%s}", sb.toString());
            webSocketHandler.sendAlert(alertMessage);
        }
    }
}

